//用户登录功能路由
const db = require('../../db/db')
// const crypto = require('crypto')

//用户登录
function login(req, res) {
    let username = req.body.username
    let password = req.body.password
    if (!password) {
        if (getUser(username)) {
            res.send({ status: 1, message: '登陆成功' })
        } else {
            //注册
            // crypto.createHash('md5').update(password).digest('base64');
            reg(username, '123456')
            res.send({ status: 1, message: '注册成功' })
        }
    } else {
        if (getUser(username, password).length) {
            res.send({ status: 1, message: '登录成功' })
        } else {
            res.send({ status: 0, message: '登录失败' })
        }
    }
}

//用户注册
function reg(username, password) {
    db.query('insert into user(username,password) values(?,?)', [username, password])
}

//用户查询
function getUser(username) {
    return new Promise((res, rej) => {
        db.query('select * from user where username = ?', [username], (result) => {
            res(result)
        })
    })

}

//用户查询
function getUser(username, password) {
    return new Promise((res, rej) => {
        db.query('select * from user where username = ? and password= ?', [username, password], (result) => {
            res(result)
        })
    })

}


module.exports = {
    login
}